package com.smarthome.api.ipc;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.smarthome.common.ipc.CommandExporter;
import com.smarthome.core.deviceManager.EquipmentDevIpcService;
import com.smarthome.domain.ipc.IpcResponse;

/**
 * 工控机请求
 *
 *
 * @author KongXiangyu
 *
 * @since 1.0
 */
@Controller
@RequestMapping("/ipc")
public class IpcController {

    private static final Logger LOGGER = LoggerFactory.getLogger(IpcController.class);

    @Resource
    private EquipmentDevIpcService equipmentDevIpcService;

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getIp", produces = { "text/json" }, method = { RequestMethod.GET })
    public void getIp(HttpServletRequest req, HttpServletResponse res) throws Exception {
        String reqStr = "";
        Map<String, String> params = new HashMap<String, String>();
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            params.put(name, req.getParameter(name));
            reqStr += name + "=" + req.getParameter(name) + "&";
        }
        LOGGER.info("服务端收到ipc-getIp消息:" + reqStr);
        String ip = getIpAddr(req);
        IpcResponse<String> response = new IpcResponse<String>();
        response.setData(ip);
        String responseStr = CommandExporter.parseJsonString(response, null);
        LOGGER.info("getIp-responseStr:" + responseStr);
        CommandExporter.sendResponse(responseStr, res);
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/recordIp", produces = { "text/json" }, method = { RequestMethod.GET })
    public void recordIp(HttpServletRequest req, HttpServletResponse res) throws Exception {
        String reqStr = "";
        Map<String, String> params = new HashMap<String, String>();
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            params.put(name, req.getParameter(name));
            reqStr += name + "=" + req.getParameter(name) + "&";
        }
        LOGGER.info("服务端收到ipc-recordIp消息:" + reqStr);
        String macAddr = req.getParameter("macAddr");
        String ip = getIpAddr(req);
        LOGGER.info("macAddr[" + macAddr + "]更新ip地址:" + ip);
        equipmentDevIpcService.updateInternetIp(macAddr, ip);
        IpcResponse<String> response = new IpcResponse<String>();
        String responseStr = CommandExporter.parseJsonString(response, null);
        LOGGER.info("recordIp-responseStr:" + responseStr);
        CommandExporter.sendResponse(responseStr, res);
    }

    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
